package com.solution.wx.my.controller;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.service.ProductService;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.constants.PublicStatus.SysSymbol;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.my.entity.UserFavoriteEntity;
import com.solution.wx.my.service.UserFavoriteService;

/**
 * 商品收藏信息web控制层
 * 
 * @author xu_cc
 * @date 2017-11-20 11:32:37
 */
@RequestMapping("/wx/favorite")
@Controller
public class FavoriteController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(FavoriteController.class);

	@Autowired
	private UserFavoriteService userFavoriteService;
	
	@Autowired
	private ProductService productService;

	/**
	 * 跳转商品收藏信息查询页面
	 * 
	 * @param UserFavorite
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-11-20 11:32:37
	 */
	@RequestMapping("/toFavoritePage")
	public String toListUserFavoritePage(HttpServletRequest request, Model model) {
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userCode", getUserCode());
			paramMap.put("isLogin", 1);
			paramMap.put("customerLevel", getCustomerLevel());
			paramMap.put("customerId", getCustomerId());
//			List<UserFavoriteEntity> favoriteList = userFavoriteService.listUserFavorite(paramMap);
			List<ProductEntity> favoriteList = productService.listUserFavoriteProduct(paramMap);
			formatProductPrice(favoriteList);
			if (null != favoriteList) {
				model.addAttribute("favoriteList", favoriteList);
				model.addAttribute("favoriteCount", favoriteList.size());
			} else {
				model.addAttribute("favoriteCount", 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "wx/my/favorite/favorite_list";
	}

	/**
	 * 跳转商品收藏信息查询页面
	 * 
	 * @param UserFavorite
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-11-20 11:32:37
	 */
	@RequestMapping("/toFavoriteEditPage")
	public String toFavoriteEditPage(HttpServletRequest request, Model model) {
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userCode", getUserCode());
			List<UserFavoriteEntity> favoriteList = userFavoriteService.listUserFavorite(paramMap);
			if (null != favoriteList) {
				model.addAttribute("favoriteList", favoriteList);
				model.addAttribute("favoriteCount", favoriteList.size());
			} else {
				model.addAttribute("favoriteCount", 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "wx/my/favorite/favorite_edit";
	}

	/**
	 * 分页查询商品收藏信息列表
	 * 
	 * @param userFavorite
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-11-20 11:32:37
	 */
	@RequestMapping("/listFavoritePage")
	@ResponseBody
	public JSONGrid listUserFavoritePage(UserFavoriteEntity userFavorite, HttpServletRequest request) {
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			PageBean pageBean = userFavoriteService.listUserFavoritePage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询商品收藏信息失败", logger, e);
		}
		return new JSONGrid();
	}

	/**
	 * 取消收藏
	 * 
	 * @param request
	 * @param idArrStr
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月20日 下午3:13:25
	 */
	@RequestMapping("/doDelFavorite")
	@ResponseBody
	public BaseReturn doDelFavorite(HttpServletRequest request, String idArrStr) {
		BaseReturn result = new BaseReturn();
		try {
			String[] idArr = idArrStr.split(SysSymbol.COMMA);
			for (String idStr : idArr) {
				if (StringUtil.isEmpty(idStr)) {
					continue;
				}
				userFavoriteService.deleteUserFavoriteById(Long.parseLong(idStr));
			}
			result.setCode(SysCode.SUCCESS);
			result.setMsg("取消收藏成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(com.solution.common.constants.PublicStatus.SysCode.ERROR);
			result.setMsg("取消收藏异常！");
		}
		return result;
	}

	/**
	 * 加入收藏
	 * 
	 * @param request
	 *            请求对象
	 * @param userFavoriteEntity
	 *            商品收藏信息实体
	 * @return
	 * @author xu_cc
	 * @date 2017-11-20 11:32:37
	 */
	@RequestMapping("/addFavorite")
	@ResponseBody
	public BaseReturn addFavorite(HttpServletRequest request, Long productId, Long productSpecCompositionId) {
		BaseReturn result = new BaseReturn();
		try {
			// 是否登录了？
			String userCode = getUserCode();
			Long favoriteId = userFavoriteService.getCountByUserCodeAndProductId(userCode, productId, productSpecCompositionId);
			if (null != favoriteId) {
				result.setCode(SysCode.SUCCESS);
				result.setMsg("已加入收藏！");
				result.setData(favoriteId);
			} else {
				UserFavoriteEntity userFavorite = new UserFavoriteEntity();
				userFavorite.setUserCode(userCode);
				userFavorite.setProductId(productId);
				userFavorite.setProductSpecCompositionId(productSpecCompositionId);
				favoriteId = userFavoriteService.saveUserFavorite(userFavorite);
				result.setData(favoriteId);
				result.setCode(SysCode.SUCCESS);
				result.setMsg("加入收藏成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("加入收藏异常！");
		}
		return result;
	}
	
	/**
	 * 格式化商品价格
	 * @param productList
	 */
	private void formatProductPrice(List<ProductEntity> productList){
		// 初始化价格显示
		DecimalFormat df = new DecimalFormat("#.00");
		if(productList != null && productList.size() > 0){
			for (ProductEntity product : productList) {
				if(product.getProductPrice() != null){
					String[] prices = df.format(product.getProductPrice()).split("\\.");
					product.setProductPriceInteger(prices[0]);
					product.setProductPriceDecimal(prices[1]);
				}
			}
		}
	}
}
